package com.ruix.app.ui.user.address;


import com.ruix.app.model.RegionModel;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;


public class RegionParserHandler extends DefaultHandler {

	private RegionModel regionModel;
	private StringBuilder builder;

	/**
	 * 存储所有的解析对象
	 */
	private List<RegionModel> provinceList;

	public RegionParserHandler() {

	}

	public List<RegionModel> getDataList() {
		return provinceList;
	}

	@Override
	public void startDocument() throws SAXException {
		// 当读到第一个开始标签的时候，会触发这个方法
		provinceList = new ArrayList<RegionModel>();
		builder = new StringBuilder();
	}


	@Override
	public void startElement(String uri, String localName, String qName,
							 Attributes attributes) throws SAXException {
		if (qName.equals("dict")) {
			regionModel = new RegionModel();
			regionModel.setName(attributes.getValue(0));
		}
		builder.setLength(0);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equals("dict")) {
			provinceList.add(regionModel);
		} else if (qName.equals("cities")){
			regionModel.setRegions(builder.toString());
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		builder.append(ch, start, length);
	}

}
